<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Qt-BaiduMap</title>

    <!-- 隐藏Logo和版权信息 -->
    <style>
        .anchorBL { display: none !important; }
        .BMap_cpyCtrl { display: none !important; }
        #mapContainer { 
            width: 100%; 
            height: 100vh; 
            margin: 0; 
            overflow: hidden 
        }
    </style>

    <!-- 异步加载百度地图API -->
    <script>
        (function() {
            var script = document.createElement('script');
            script.src = 'https://api.map.baidu.com/api?type=webgl&v=3.0&ak=BT0O9nsDZomWLvDiEdPHXNZeRnUhy9S4&callback=initMap';
            script.async = true;
            document.head.appendChild(script);
        })();
    </script>
    <script src="./qwebchannel.js"></script>
</head>
<body>
    <div id="mapContainer"></div>

    <script type="text/javascript">
        var map = null;
        var bridge;
        
        // 复合标记对象
        var boxMarker = { point: null, icon: null};
        var boxMarker1 = { point: null, icon: null};
        var carMarker = { point: null, icon: null};
        var droneMarker = { point: null, icon: null};

        var drivingWay = null; // 驾驶路线对象

        function initMap() {
            map = new BMapGL.Map('mapContainer');
            map.centerAndZoom(new BMapGL.Point(122.08930442831216,37.538181449863764), 15);
            map.enableScrollWheelZoom(true);
            map.setDisplayOptions({
                poiIcon: false
            });

             // 创建定位控件
            var locationControl = new BMapGL.LocationControl({
                // 控件的停靠位置（可选，默认左上角）
                anchor: BMAP_ANCHOR_TOP_RIGHT,
                // 控件基于停靠位置的偏移量（可选）
                offset: new BMapGL.Size(20, 20)
            });
            // 将控件添加到地图上
            map.addControl(locationControl);

            // 添加定位事件
            locationControl.addEventListener("locationSuccess", function(e){
                var address = '';
                address += e.addressComponent.province;
                address += e.addressComponent.city;
                address += e.addressComponent.district;
                address += e.addressComponent.street;
                address += e.addressComponent.streetNumber;
                alert("当前定位地址为：" + address);
            });
            locationControl.addEventListener("locationError",function(e){
                alert(e.message);
            });

            new QWebChannel(qt.webChannelTransport, function(channel) {
                bridge = channel.objects.bridge;
                bridge.emitIsLoad();
            });
        }

        function setCenter(lng, lat) {
            if(map) map.setCenter(new BMapGL.Point(lng, lat));
        }

        // 创建绿色圆点图标（Base64 SVG）
        function createGreenDotIcon() {
            return new BMapGL.Icon(
                '',
                //圆点大小
                new BMapGL.Size(20, 20),
                { anchor: new BMapGL.Size(15, 15) }
            );
        }

        // 通用标记创建函数
        function createCompositeMarker(lng, lat, iconPath, targetObj) {
            // 移除旧覆盖物
            if(targetObj.point) map.removeOverlay(targetObj.point);
            if(targetObj.icon) map.removeOverlay(targetObj.icon);

            // 创建绿色圆点
            targetObj.point = new BMapGL.Marker(
                new BMapGL.Point(lng, lat),
                { icon: createGreenDotIcon() }
            );
            
            // 创建顶部图标
            targetObj.icon = new BMapGL.Marker(
                new BMapGL.Point(lng, lat),
                { 
                    //icon大小
                    icon: new BMapGL.Icon(iconPath, new BMapGL.Size(45, 45), {
                        anchor: new BMapGL.Size(25, 60) // 向上偏移
                    })
                }
            );
            // 添加覆盖物
            [targetObj.point, targetObj.icon].forEach(o => map.addOverlay(o));
            
            // 层级控制（异步设置z-index）
            setTimeout(() => {
                const markers = document.querySelectorAll('.BMapGL_Marker');
                markers.forEach(marker => {
                    if(marker.querySelector('img[src*=".ico"]')) {
                        marker.style.zIndex = 501; // 顶层图标
                    } else if(marker.querySelector('circle')) {
                        marker.style.zIndex = 500; // 中间圆点
                    }
                });
                document.querySelectorAll('.BMapGL_Label').forEach(label => {
                    label.style.zIndex = 499; // 底层坐标
                });
            }, 500);

            // 添加点击事件(显示坐标信息)
            // 创建信息窗口
            var opts = {
                width: 10,
                height: 10,
                title: '坐标'
            };
            var infoWindow = new BMapGL.InfoWindow(`(${lng}, ${lat})`, opts);
            targetObj.icon.addEventListener('click', function () {
                map.openInfoWindow(infoWindow, new BMapGL.Point(lng, lat)); // 开启信息窗口
            });
        }

        // 修改后的标记函数
        function setBoxPoint(lng, lat) {
            createCompositeMarker(lng, lat, '../img/favicon.ico', boxMarker);
        }

        function setBoxPoint1(lng, lat) {
            createCompositeMarker(lng, lat, '../img/favicon.ico', boxMarker1);
        }

        function setCurrentCarPoint(lng, lat) {
            createCompositeMarker(lng, lat, '../img/favicon (1).ico', carMarker);
        }

        function setCurrentDronePoint(lng, lat) {
            createCompositeMarker(lng, lat, '../img/favicon (2).ico', droneMarker);
        }

        // 删除函数需同步修改
        function deleteBoxPoint() {
            [boxMarker.point, boxMarker.icon, boxMarker.label]
                .filter(o => o).forEach(o => map.removeOverlay(o));
            boxMarker = { point: null, icon: null, label: null };
        }

        function deleteCurrentCarPoint() {
            [carMarker.point, carMarker.icon, carMarker.label]
                .filter(o => o).forEach(o => map.removeOverlay(o));
            carMarker = { point: null, icon: null, label: null };
        }

        function deleteCurrentDronePoint() {
            [droneMarker.point, droneMarker.icon, droneMarker.label]
                .filter(o => o).forEach(o => map.removeOverlay(o));
            droneMarker = { point: null, icon: null, label: null };
        }
        
        function setWay(sLng, sLat, eLng, eLat) {
            deleteWay(); // 删除旧路线
            // 创建新的路线覆盖物
            var startPoint = new BMapGL.Point(sLng, sLat);
            var endPoint = new BMapGL.Point(eLng, eLat);
            drivingWay = new BMapGL.DrivingRouteLine(map, {
                renderOptions: { map: map, autoViewport: true ,enableDragging:true},
                onPolylinesSet: function (polylines) {
                    // 获取路线覆盖物
                    var polyline = polylines[0];
                    // 获取路线覆盖物上的点,用最精确的精度获取
                    var points = polyline.getPath();
                    // 获取路线覆盖物上的点个数
                    var pointNum = points.length;
                    // 获取路线覆盖物上的点
                    var point = points[pointNum - 1];
                    //将points转化为json字符串
                    var pointsJson = JSON.stringify(points.map(p => ({ lng: p.lng.toFixed(7), lat: p.lat.toFixed(7) })));
                    // 发送数据到Qt
                    bridge.receiveRouteCoordinates(pointsJson);
                }
            });
            drivingWay.search(startPoint, endPoint,{});
        }
        function deleteWay() {
            if(drivingWay) {
                // 清除路线覆盖物
                drivingWay.getResults().getPlan(0).getRoutes().forEach(route => {
                    map.removeOverlay(route);
                });
                drivingWay = null;
            }
        }
   </script>
</body>
</html>